package com.jt.base;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.ArrayList;
import java.util.List;


@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {

  /** 支持跨域配置 */
  @Override
  protected void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedMethods("*").allowedOrigins("*").allowedHeaders("*");
  }

  /** 静态资源配置 */
  @Override
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations("classpath:/static/","classpath:/templates/");
    super.addResourceHandlers(registry);
  }
  /**
   * 支持*.do请求
   * @param configurer
   */
  @Override
  public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer.setUseSuffixPatternMatch(true);
    configurer.setUseTrailingSlashMatch(true);
  }
  /** json设置 */
  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);

    // 初始化转换器
    FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
    // 初始化一个转换器配置
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    //处理中文乱码问题
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConvert.setSupportedMediaTypes(fastMediaTypes);
    // 将配置设置给转换器并添加到HttpMessageConverter转换器列表中
    fastConvert.setFastJsonConfig(fastJsonConfig);

    converters.add(fastConvert);
  }
}
